<template>
	<el-dialog v-model="visible" :title="dataForm.id ? '编辑规则' : '新增规则'" :close-on-click-modal="false">
		<el-form ref="dataFormRef" label-width="100" :model="dataForm" :rules="dataRules">
			<el-form-item prop="ruleName" label="规则名称">
				<el-input v-model="dataForm.ruleName" placeholder="请输入规则名称"></el-input>
			</el-form-item>
			<!-- <el-form-item prop="status" label="状态">
				<el-switch v-model="dataForm.status"></el-switch> {{ dataForm.status ? '开启' : '关闭' }}
			</el-form-item> -->
			<el-form-item prop="remark" label="备注">
				<el-input v-model="dataForm.remark" :rows="8" maxlength="200" type="textarea" show-word-limit></el-input>
			</el-form-item>
		</el-form>

		<template #footer>
			<el-button @click="visible = false">取消</el-button>
			<el-button type="primary" :loading="btnLoading" @click="saveFormBtn">确定</el-button>
		</template>
	</el-dialog>
</template>
<script setup lang="ts">
import { ref, reactive, nextTick } from 'vue'
import { addRule } from '@/api/patient-primary/rule-mana'
import { ElMessage } from 'element-plus'

const visible = ref(false)
const dataFormRef = ref()
const dataForm = reactive({
	name: '',
	status: false,
	remark: '',
	ifInvalid: 1
})

const emit = defineEmits(['close'])

const btnLoading = ref(false)

const dataRules = ref({
	ruleName: [{ required: true, message: '规则名称不能为空', trigger: 'blur' }],
	// remark: [
	// 	{
	// 		validator: (rule, value, callback) => {
	// 			if (value && value.length) {
	// 				if (value.length > 200) {
	// 					callback(new Error('备注不能超过200个字符'))
	// 					dataForm.remark = value.slice(0, 200)
	// 				} else {
	// 					callback()
	// 				}
	// 			} else {
	// 				callback()
	// 			}
	// 		}
	// 	}
	// ]
	// status: [{ required: true, message: '状态不能为空', trigger: 'change' }]
})

const init = data => {
	visible.value = true

	nextTick(() => {
		// 重置表单数据
		if (dataFormRef.value) {
			dataFormRef.value.resetFields()
		}

		if (data) {
			Object.assign(dataForm, data)

			// dataForm.status = dataForm.ifInvalid == 0 ? true : false
		} else {
			dataForm.id = ''
			dataForm.ifInvalid = 1
		}
	})
}

const saveFormBtn = () => {
	dataFormRef.value.validate(valid => {
		if (valid) {
			// 表单验证通过，执行保存操作
			btnLoading.value = true

			// if (dataForm.status) {
			// 	dataForm.ifInvalid = 0
			// } else {
			// 	dataForm.ifInvalid = 1
			// }
			addRule(dataForm)
				.then(res => {
					ElMessage.success({
						message: '保存成功',
						duration: 500,
						onClose: () => {
							btnLoading.value = false
							visible.value = false
							emit('close')
						}
					})
				})
				.catch(() => {
					btnLoading.value = false
				})
		}
	})
}

defineExpose({
	init
})
</script>
<style lang="scss" scoped></style>
